package com.ruoyi.system.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.TzCollectionOrder;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TzCollectionOrderMapper;
import com.ruoyi.system.service.TzCollectionOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;
import java.util.Set;


@Service
public class TzCollectionOrderServiceImpl extends ServiceImpl<TzCollectionOrderMapper, TzCollectionOrder> implements TzCollectionOrderService {


    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<TzCollectionOrder> pageList(PageDomain pageDomain, TzCollectionOrder query) {
        Page<TzCollectionOrder> page = new Page(pageDomain.getPageNum(), pageDomain.getPageSize());
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        SysUser  user=sysUserMapper.selectUserById(loginUser.getUserId());
        Set<String> roles = loginUser.getPermissions();
        if (!loginUser.getUsername().equals("admin")) {

            if (!roles.contains("business:order:allot")) {
                query.setUserId(loginUser.getUserId());
            }
        }
        Long tenantId = SecurityUtils.getMerchantId();
        if (tenantId != null && tenantId.equals(0)) {
            query.setTenantId(tenantId.toString());
        }

        IPage<TzCollectionOrder> pageList = page(page,
                Wrappers.<TzCollectionOrder>lambdaQuery()
                        .eq(ObjectUtils.isNotNull(query.getId()), TzCollectionOrder::getId, query.getId())
                        .eq(ObjectUtils.isNotEmpty(query.getTenantId()), TzCollectionOrder::getTenantId, query.getTenantId())
                        .eq(ObjectUtils.isNotEmpty(query.getOutOrderId()), TzCollectionOrder::getOutOrderId, query.getOutOrderId())
                        .eq(ObjectUtils.isNotEmpty(query.getOutOrderNo()), TzCollectionOrder::getOutOrderNo, query.getOutOrderNo())
                        .eq(ObjectUtils.isNotEmpty(query.getProductName()), TzCollectionOrder::getProductName, query.getProductName())
                        .eq(ObjectUtils.isNotEmpty(query.getProductInfo()), TzCollectionOrder::getProductInfo, query.getProductInfo())
                        .eq(ObjectUtils.isNotEmpty(query.getCustomerName()), TzCollectionOrder::getCustomerName, query.getCustomerName())
                        .eq(ObjectUtils.isNotEmpty(query.getMobile()), TzCollectionOrder::getMobile, query.getMobile())
                        .eq(ObjectUtils.isNotEmpty(query.getAddress()), TzCollectionOrder::getAddress, query.getAddress())
                        .eq(ObjectUtils.isNotEmpty(query.getIdCard()), TzCollectionOrder::getIdCard, query.getIdCard())
                        .eq(ObjectUtils.isNotEmpty(query.getIdCardFront()), TzCollectionOrder::getIdCardFront, query.getIdCardFront())
                        .eq(ObjectUtils.isNotEmpty(query.getIdCardBack()), TzCollectionOrder::getIdCardBack, query.getIdCardBack())
                        .eq(ObjectUtils.isNotNull(query.getTotalAmount()), TzCollectionOrder::getTotalAmount, query.getTotalAmount())
                        .eq(ObjectUtils.isNotNull(query.getRepaidAmount()), TzCollectionOrder::getRepaidAmount, query.getRepaidAmount())
                        .eq(ObjectUtils.isNotNull(query.getUnpaidAmount()), TzCollectionOrder::getUnpaidAmount, query.getUnpaidAmount())
                        .eq(ObjectUtils.isNotNull(query.getTotalPeriods()), TzCollectionOrder::getTotalPeriods, query.getTotalPeriods())
                        .eq(ObjectUtils.isNotNull(query.getRepaidPeriods()), TzCollectionOrder::getRepaidPeriods, query.getRepaidPeriods())
                        .eq(ObjectUtils.isNotNull(query.getUnpaidPeriods()), TzCollectionOrder::getUnpaidPeriods, query.getUnpaidPeriods())
                        .eq(ObjectUtils.isNotEmpty(query.getRepaymentPlan()), TzCollectionOrder::getRepaymentPlan, query.getRepaymentPlan())
                        .eq(ObjectUtils.isNotEmpty(query.getContractUrl()), TzCollectionOrder::getContractUrl, query.getContractUrl())
                        .eq(ObjectUtils.isNotEmpty(query.getRiskReportUrl()), TzCollectionOrder::getRiskReportUrl, query.getRiskReportUrl())
                        .eq(ObjectUtils.isNotNull(query.getOrderStatus()), TzCollectionOrder::getOrderStatus, query.getOrderStatus())
                        .eq(ObjectUtils.isNotNull(query.getOverdueDays()), TzCollectionOrder::getOverdueDays, query.getOverdueDays())
                        .eq(ObjectUtils.isNotNull(query.getUserId()), TzCollectionOrder::getUserId, query.getUserId())
                        .eq(ObjectUtils.isNotNull(query.getCollectionStatus()), TzCollectionOrder::getCollectionStatus, query.getCollectionStatus())
                        .eq(ObjectUtils.isNotNull(query.getCollectionTimes()), TzCollectionOrder::getCollectionTimes, query.getCollectionTimes())
                        .eq(ObjectUtils.isNotNull(query.getLastCollectionTime()), TzCollectionOrder::getLastCollectionTime, query.getLastCollectionTime())
                        .eq(ObjectUtils.isNotNull(query.getSettlementAmount()), TzCollectionOrder::getSettlementAmount, query.getSettlementAmount())
                        .eq(ObjectUtils.isNotEmpty(query.getCollectionRemark()), TzCollectionOrder::getCollectionRemark, query.getCollectionRemark())
                        .eq(ObjectUtils.isNotNull(query.getCreateDept()), TzCollectionOrder::getCreateDept, query.getCreateDept())
                        .eq(ObjectUtils.isNotEmpty(query.getDelFlag()), TzCollectionOrder::getDelFlag, query.getDelFlag())
                        .eq(ObjectUtils.isNotEmpty(query.getCreateBy()), TzCollectionOrder::getCreateBy, query.getCreateBy())
                        .eq(ObjectUtils.isNotNull(query.getCreateTime()), TzCollectionOrder::getCreateTime, query.getCreateTime())
                        .eq(ObjectUtils.isNotEmpty(query.getUpdateBy()), TzCollectionOrder::getUpdateBy, query.getUpdateBy())
                        .eq(ObjectUtils.isNotNull(query.getUpdateTime()), TzCollectionOrder::getUpdateTime, query.getUpdateTime())
                        .eq(ObjectUtils.isNotEmpty(query.getRemark()), TzCollectionOrder::getRemark, query.getRemark())

        );
        return pageList.getRecords();
    }


    public boolean update(TzCollectionOrder order) {
        return this.updateById(order);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean bindUser(Long id, Long userId) {

        SysUser queryUser = new SysUser();

//        queryUser.setDeptId(deptId);
        if (userId == null|| userId==0) {
            queryUser.setUserType("employee");
        }else {
            queryUser.setUserId(userId);
        }
        List<SysUser> userList = sysUserMapper.selectUserList(queryUser);
        if (ObjectUtils.isEmpty(userList)) {
            throw new ServiceException("部门不存在用户");
        }
        TzCollectionOrder order= this.getById(id);
        if (order.getCollectionStatus()!=0){
            order.setCollectionTimes(ObjectUtils.isEmpty(order.getCollectionTimes())?1:order.getCollectionTimes()+1);
            this.updateById(order);
        }
        SysUser user = new SysUser();
        // 根据客服权重占比,将订单分配给后台客服
        if (ObjectUtils.isEmpty(userId)) {
            user = selectUser(userList);
        } else {
            user = userList.stream().filter(u -> u.getUserId().equals(userId)).findFirst().orElse(null);
        }
        return lambdaUpdate()
                .eq(TzCollectionOrder::getId, id)
                .set(TzCollectionOrder::getUserId, user.getUserId())
                .update();
    }

    @Override
    public List<SysUser> getUserList(Long deptId) {
        SysUser queryUser = new SysUser();
        queryUser.setDeptId(deptId);
        List<SysUser> userList = sysUserMapper.selectUserList(queryUser);
        return userList;
    }


    public SysUser selectUser(List<SysUser> users) {
        int totalWeight = 0;
        for (SysUser user : users) {
            totalWeight += user.getWeight();
        }

        Random random = new Random();
        int randomValue = random.nextInt(totalWeight);

        int cumulativeWeight = 0;
        for (SysUser user : users) {
            cumulativeWeight += user.getWeight();
            if (cumulativeWeight > randomValue) {
                return user;
            }
        }
        throw new IllegalStateException("没有可用的用户");
    }


}
